package com.yunb.hyloglog;

import org.omg.CORBA.PRIVATE_MEMBER;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Random;
import java.util.concurrent.TimeUnit;


@Service
public class HLLService {

    private static final Logger logger = LoggerFactory.getLogger(HLLService.class);

    @Autowired
    private JedisPool jedisPool;

    @Autowired
    private RedisTemplate redisTemplate;


   @PostConstruct
    public void useHll(){
//       Jedis jedis = null;
//       try {
//
//           jedis = jedisPool.getResource();
//
//           Jedis finalJedis = jedis;
//
//           new Thread(() -> {
//               String ipstr = null;
//               for (int i = 1; i <=200 ; i++) {
//                   Random random = new Random();
//                   ipstr = random.nextInt(256)+"."+random.nextInt(256)+"."+random.nextInt(256)+"."+random.nextInt(256);
//                   long hll = finalJedis.pfadd("taobao",ipstr);
//                   logger.info("ip={},该IP地址访问首页的次数={}",ipstr,hll);
//                   try {TimeUnit.SECONDS.sleep(2);} catch (InterruptedException e) {throw new RuntimeException(e);}
//
//               }
//           }, "t1").start();
//       } catch (Exception e) {
//
//       } finally {
//           jedis.close();
//       }


       new Thread(() -> {
           String ipstr = null;
           for (int i = 1; i <=200 ; i++) {
               Random random = new Random();
               ipstr = random.nextInt(256)+"."+random.nextInt(256)+"."+random.nextInt(256)+"."+random.nextInt(256);
               long jingdong =redisTemplate.opsForHyperLogLog().add("jingdong",ipstr);
               logger.info("ip={},该IP地址访问首页的次数={}",ipstr,jingdong);
               try {TimeUnit.SECONDS.sleep(2);} catch (InterruptedException e) {throw new RuntimeException(e);}

           }
       }, "t1").start();


    }
    public long uv(){
//        Jedis jedis = null;
//        try {
//
//            jedis = jedisPool.getResource();
//
//
//        } catch (Exception e) {
//
//        } finally {
//            jedis.close();
//        }
       //pfcount
        //return jedis.pfcount("taobao");
        return redisTemplate.opsForHyperLogLog().size("jingdong");
    }

}
